package com.lintntu;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lintntu.pojo.Result;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Objects;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
//    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.grade_group);
    EditText id,pwd;
    TextView textView;
    Button login;
    String [] logindatas={"","","null","",""};//0.账号，1.密码,2.运营商，3.ip，4.一个随机数
    RadioButton o1,o2,o3,o4;
    boolean everLogin = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id=findViewById(R.id.id);
        pwd=findViewById(R.id.pwd);
        login=findViewById(R.id.login);
        login.setOnClickListener((View.OnClickListener) this);
        textView=findViewById(R.id.textView);
         o1 =findViewById(R.id.operator1);
         o2 =findViewById(R.id.operator2);
         o3 =findViewById(R.id.operator3);
         o4 =findViewById(R.id.operator4);
         readLoginDataInfo(findViewById(R.id.login));
//        Toast.makeText(getApplicationContext(), logindatas[2], Toast.LENGTH_LONG).show();
    }

    public void onClick(View v) {
        onRadioButtonClicked(findViewById(R.id.grade_group));

        saveLoginDataInfo(findViewById(R.id.login));
        if (readLoginDataInfo(findViewById(R.id.login))){
            Integer temp = (int)(Math.random()*60000)+50000;
            logindatas[4]= temp.toString();
            getIP();
            send();
        }
        else {
            Integer temp = (int)(Math.random()*60000)+50000;
            logindatas[4]= temp.toString();
            getIP();
            send();
        }
//        saveLoginDataInfo(findViewById(R.id.login));

    }

    /***
     * 读取并且设置信息
     * @param view
     */
    public boolean readLoginDataInfo(View view){
        String datas="";
        try {
            FileInputStream fis = openFileInput("loginData");
            byte[] buffer;
            try {
                buffer= new byte[fis.available()];
                fis.read(buffer);
                datas = new String(buffer);
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        String [] data=datas.split(" ");
        id.setText(data[0]);
        pwd.setText(data[1]);
        logindatas[0]=data[0];
        logindatas[1]=data[1];
        try {
            logindatas[2]=data[2];
        }
        catch (ArrayIndexOutOfBoundsException e){
            logindatas[2]="";
        }
        if (Objects.equals(logindatas[2], "")){
            o1.toggle();
        }
        if (Objects.equals(logindatas[2], "cmcc")){
            o2.toggle();
        }
        if (Objects.equals(logindatas[2], "telecom")){
            o3.toggle();
        }
        if (Objects.equals(logindatas[2], "unicom")){
            o4.toggle();
        }
        return true;
    }

    //判断保存的登录文件是否存在
    public boolean fileIsExists(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists())
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }

    public void saveLoginDataInfo(View view){
        String saveInfo = id.getText().toString();
        saveInfo+=" "+pwd.getText().toString();
        logindatas[0]=id.getText().toString();
        logindatas[1]=pwd.getText().toString();
        saveInfo+=" "+logindatas[2];
//        Toast.makeText(getApplicationContext(), saveInfo, Toast.LENGTH_LONG).show();
        try {
            FileOutputStream fos= openFileOutput("loginData", Context.MODE_PRIVATE);
            fos.write(saveInfo.getBytes());
            fos.close();
//            Toast.makeText(getApplicationContext(), "正在保存文件", Toast.LENGTH_LONG).show();
        }
        catch (Exception e){
            e.printStackTrace();
//            Toast.makeText(getApplicationContext(), "保存文件出错", Toast.LENGTH_LONG).show();
        }
    }

    private void send() {
        //开启线程，发送请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                String requestUrl = "http://210.29.79.141:801/eportal/?c=Portal&a=login&callback=dr1003&login_method=1&user_account=%2C1%2C"+logindatas[0]+"%40"+logindatas[2]+"&user_password="+logindatas[1]+"&wlan_user_ip="+logindatas[3]+"&wlan_user_ipv6=&wlan_user_mac=000000000000&wlan_ac_ip=&wlan_ac_name=&jsVersion=3.3.2&v="+logindatas[4];
                try {
                    URL url = new URL(requestUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    //设置请求方法
                    connection.setRequestMethod("GET");
                    //设置连接超时时间（毫秒）
                    connection.setConnectTimeout(5000);
                    //设置读取超时时间（毫秒）
                    connection.setReadTimeout(5000);

                    //返回输入流
                    InputStream in = connection.getInputStream();

                    //读取输入流
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    Gson gson=new Gson();
                    //解析对象：第一个参数：待解析的字符串 第二个参数结果数据类型的Class对象
                    String str=result.toString();
                    str= str.replaceAll("dr1003\\(|\\)","");
                    Result resultClass =gson.fromJson(str, Result.class);


                        show(resultClass.toString());

                } catch (MalformedURLException | ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {//关闭连接
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /***
     * 选择运营商
     * @param view
     */
    public void onRadioButtonClicked(View view) {
        if (o1.isChecked()){
            logindatas[2]="";
//            Toast.makeText(getApplicationContext(), "点击了校园网", Toast.LENGTH_LONG).show();
            //校园网
        }
        else if(o2.isChecked()){
            logindatas[2]="cmcc";
//            Toast.makeText(getApplicationContext(), "点击了移动网", Toast.LENGTH_LONG).show();

            //移动
        }
        else if(o3.isChecked()){
            logindatas[2]="telecom";
//            Toast.makeText(getApplicationContext(), "点击了电信网", Toast.LENGTH_LONG).show();

            //电信
        }
        else if(o4.isChecked()){
            logindatas[2]="unicom";
//            Toast.makeText(getApplicationContext(), "点击了联通网", Toast.LENGTH_LONG).show();

            //联通
        }
    }


    /**
     * 使用WifiManager获取ip地址
     */
    public void getIP(){
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();

        logindatas[3] = (ipAddress & 0xff) + "." + (ipAddress>>8 & 0xff) + "." + (ipAddress>>16 & 0xff) + "." + (ipAddress >> 24 & 0xff);
//        Toast.makeText(getApplicationContext(),logindatas[3] , Toast.LENGTH_LONG).show();
            if(!wifiInfo.getBSSID().equals("NTU")){
                show("没有连接到NTU，检查WiFi是否打开");

            }
//        Toast.makeText(getApplicationContext(),logindatas[3] , Toast.LENGTH_LONG).show();
    }

    /**
     * 展示
     *
     * @param result
     */
    private void show(String result) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText(result);
            }
        });
    }

}